#include "epoll_chat_tcp.h"

// 初始化
int tcp_server_init(const char *ip, int port, int backlog)
{
    int fd = socket(PF_INET, SOCK_STREAM, 0);
    if (-1 == fd)
        return fd;
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_port = htons(port);
    saddr.sin_addr.s_addr = inet_addr(ip);
    int ok = 1;
    if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ok, sizeof ok))
    {
        perror("setsockopt");
        return -1;
    }

    if (-1 == bind(fd, (void *)&saddr, sizeof saddr))
        return -1;

    if (-1 == listen(fd, backlog))
        return -1;
    puts("listen...");
    return fd;
}
// 等待连接
int tcp_server_wait(int listenfd)
{
    struct sockaddr_in caddr; // 用来存储连接的客户端的IP PORT
    socklen_t len = sizeof caddr;

    int nfd = accept(listenfd, (void *)&caddr, &len);
    if (-1 == nfd)
        return -1;
    printf("Client %s:%d connected!\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
    return nfd;
}
int sendMsg(ND *head, int fd)
{

    if (NULL == head)
    {
        puts("invalid fd_list NULL");
        exit(1);
    }
    char buf[1024];
    int ID;
    recv(fd, buf, 1024, MSG_NOSIGNAL);
    puts(buf);
    int len =strlen(buf);
   // printf("%d\n",len);
    if (0 == strncmp(buf, "->", 2))
    {
    }
    else
    {
        while (head = head->successor_node)
        {
            if (head->data == fd)
            {
                continue;
            }
            if (0 == len)
            {
                break;
            }
            
            printf("%d\n",head->data);
            send(head->data, buf, len, MSG_NOSIGNAL);
            bzero(buf,1024);
        }
    }
}